import React, { Component } from "react";
import "./05.css";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export default class ColorPicker extends Component {
  // 1. 声明状态
  state = {
    r: 0,
    g: 0,
    b: 0,
  };

  //声明表单元素的 onChange 事件回调
  change = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  //声明 div 点击的事件回调
  getColor = async () => {
    //解构赋值
    let { r, g, b } = this.state;
    //获取颜色值
    let color = `rgb(${r},${g},${b})`;
    try {
      //将文本写入到剪切板
      await navigator.clipboard.writeText(color);
      //提示
      toast.success('操作成功！', { position: toast.POSITION.TOP_RIGHT });
    } catch (e) {
      toast.error('操作失败！', { position: toast.POSITION.TOP_RIGHT });
    }
  };

  render() {
    //解构赋值
    let { r, g, b } = this.state;

    return (
      <div className="picker-container">
        {/* 颜色显示区 */}
        <div
          onClick={this.getColor}
          className="color-show"
          style={{ background: `rgb(${r},${g},${b})` }}
        ></div>
        <hr />
        {/* 颜色控制区 */}
        <div className="color-control">
          R:
          <input
            type="range"
            name="r"
            min={0}
            max={255}
            value={r}
            onChange={this.change}
          />
          <br />
          G:
          <input
            type="range"
            name="g"
            min={0}
            max={255}
            value={g}
            onChange={this.change}
          />
          <br />
          B:
          <input
            type="range"
            name="b"
            min={0}
            max={255}
            value={b}
            onChange={this.change}
          />
          <br />
        </div>
        <ToastContainer />
      </div>
    );
  }
}
